<template>
  <div id="teamCfg">
    <div class="">
      <div class="">
        <div :style="{ padding: '12px' }">
          <el-form
            ref="formref"
            size="default"
            :rules="rules"
            :model="form"
            label-width="120px"
            :form="form"
            label-position="right"
          >
            <el-form-item label="学校团队名称" prop="name">
              <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="学校团队介绍">
              <el-input
                type="textarea"
                :rows="10"
                placeholder="学校团队介绍"
                v-model="form.info"
              ></el-input>
            </el-form-item>

            <el-form-item label="学校团队宣传图" prop="type">
              <el-upload
                v-model:file-list="fileList"
                action="/"
                :show-file-list="true"
                accept=".png,.svg,.jpg"
                multiple
                :on-preview="handlePictureCardPreview"
                list-type="picture-card"
                :http-request="uploadBanner"
                class="avatar-uploader"
              >
                <el-icon>
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>

            <el-form-item label="学校团队Logo" prop="type">
              <el-upload
                action="/"
                accept=".png,.svg,.jpg"
                :show-file-list="false"
                :http-request="requestSaasLogo"
                class="avatar-uploader"
              >
                <img
                  v-if="form?.other?.saasTeamLogo"
                  :src="form?.other?.saasTeamLogo"
                  class="avatar"
                />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon> </el-upload
              >&nbsp;
              <el-button
                v-if="form?.other?.saasTeamLogo"
                type=""
                size="default"
                :icon="Delete"
                circle
                @click="delIcon"
              />
            </el-form-item>
            <el-form-item label="学校数据标题" prop="type">
              <el-input
                v-model="form.other!.datatitle"
                :maxlength="15"
                clearable
              />
            </el-form-item>
            <!-- <el-row :gutter="10">
              <el-form-item label="AI思路提示" prop="ideaTips">
                <el-switch size="" v-model="form.other.ideaTips" inline-prompt active-text="显示" inactive-text="隐藏"
                  style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949">
                </el-switch>
              </el-form-item>
              <el-form-item label="AI代码协助" prop="codeHelp">
                <el-switch size="" v-model="form.other.codeHelp" inline-prompt active-text="显示" inactive-text="隐藏"
                  style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949">
                </el-switch>
              </el-form-item>
              <el-form-item label="AI分析比赛" prop="activitySummarize">
                <el-switch size="" v-model="form.other.activitySummarize" inline-prompt active-text="显示"
                  inactive-text="隐藏" style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949">
                </el-switch>
              </el-form-item>
              <el-form-item label="AI分析比赛成员" prop="activityUserSummarize">
                <el-switch size="" v-model="form.other.activityUserSummarize" inline-prompt active-text="显示"
                  inactive-text="隐藏" style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949">
                </el-switch>
              </el-form-item>
            </el-row> -->
            <el-form-item>
              <el-button type="primary" size="default" @click="start"
                >刷新</el-button
              >
              <el-button type="primary" size="default" @click="submit"
                >保存</el-button
              >
            </el-form-item>
          </el-form>
          <!-- 预览图 -->
          <el-dialog v-model="dialogVisible" title="预览">
            <template #header>
              <span class="icon-text el-dialog__header-title">
                <el-icon class="text-primary">
                  <Guide />
                </el-icon>
                预览
              </span>
            </template>
            <el-image :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Delete, Plus } from "@element-plus/icons-vue";
import { ElForm, ElMessage, UploadProps, UploadUserFile } from "element-plus";
import { computed, onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { asyncgetteam, asyncteamchangeteam } from "../../../api";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import updateoss from "../../../util/updateoss";
import { Team } from "../data";
import { teamrules } from "../data/formrules";

const store = useStore(Storekey);
const user = computed<Studycodemodel.Iuser>(() => {
  return store.getters.getuser;
});
const teamId = computed(() => {
  return user.value?.teamid;
});

const data = reactive(Object.assign({}, Team));
const isAdmin = computed(() => {
  if (!user.value) return 0;
  if (data?.userid === user.value.ID) return 1;
  const a = data?.teamuser?.find((v) => v.userid === user.value.ID);
  if (a) {
    return a.isAdmin;
  }
  if (user.value.remarks === "销售助教") return 1;
  return 0;
});

const form = reactive(Object.assign({}, Team));
const formref = ref<typeof ElForm>();
const rules = teamrules;
const router = useRouter();

onMounted(() => {
  if (!isAdmin) {
    ElMessage.error("没有权限");
    router.push("/");
  }
  start();
});

async function start() {
  const d = await asyncgetteam({ ID: teamId.value });
  Object.assign(data, d);
  Object.assign(
    form,
    d,
    // 默认
    {
      info: d.info ? d.info : `欢迎来到${d.name}`,
      other: d.other ? d.other : {},
    }
  );
  // 默认banner
  fileList.value = form?.other?.banner || [
    {
      name: "banner01.png",
      url: "https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/saas-banner.png",
    },
  ];
  // saasTeamLogoFileList.value = form?.other?.saasTeamLogo ? [
  //   {
  //     url: form?.other?.saasTeamLogo,
  //     name: "saasTeamLogo"
  //   }
  // ] : []
}

async function submit() {
  form.other = {
    ...form.other,
    banner: fileList.value.map((e) => ({ name: e.name, url: e.url })),
    // saasTeamLogo: saasTeamLogoFileList.value[0]?.url
  };
  if (isAdmin.value && data?.ID) {
    Object.assign(form, { teamid: data.ID });
    try {
      await asyncteamchangeteam(form);
      ElMessage.success("操作成功!");
      start();
    } catch (error) {
      ElMessage.error(error);
    }
  } else {
    ElMessage.error("你不是管理员无法更改!");
  }
}

const saasTeamLogoFileList = ref<UploadUserFile[]>([]);
// saas团队logo上传
async function requestSaasLogo(file: { file: File }) {
  const { name } = await updateoss([file.file]);
  if (!form.other) {
    form.other = {};
  }
  form.other.saasTeamLogo = `https://cdn.hterobot.com/${name}`;
}
// async function requestSaasLogo(file: { file: File }) {
//   const uid = file.file.uid
//   const { name } = await updateoss([file.file]);

//   let idx = saasTeamLogoFileList.value.findIndex(e => uid === e.uid)
//   if (idx !== -1) {
//     saasTeamLogoFileList.value.splice(idx, 1, { name, url: `https://cdn.hterobot.com/${name}` })
//   } else {
//     saasTeamLogoFileList.value.push({ name, url: `https://cdn.hterobot.com/${name}` })
//   }
// }

const fileList = ref<UploadUserFile[]>([]);
// banner上传- other
async function uploadBanner(file: { file: File }) {
  const uid = file.file.uid;
  const { name } = await updateoss([file.file]);

  let idx = fileList.value.findIndex((e) => uid === e.uid);
  if (idx !== -1) {
    fileList.value.splice(idx, 1, {
      name,
      url: `https://cdn.hterobot.com/${name}`,
    });
  } else {
    fileList.value.push({ name, url: `https://cdn.hterobot.com/${name}` });
  }
}

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

// 删除团队 icon
function delIcon() {
  if (!form.other) {
    form.other = {};
  }
  form.other.saasTeamLogo = "";
}
</script>

<style scoped>
.avatar {
  height: 64px;
  min-width: 64px;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  background-color: var(--el-fill-color-lighter);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
}
</style>
